// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-05 19:48
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.TREE;

import com.DataStruct.Tree.TwoBinaryTree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class IsBalanced {
    /**
     * 判断给定树是否是平衡二叉树
     */
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }

        int LH = 0;
        int RH = 0;
        if (root.left != null) {
            LH = getHigh(root.left);
        }
        if (root.right != null) {
            RH = getHigh(root.right);
        }
        System.out.println(root.val + "--" + RH);
        System.out.println(root.val + "--" + LH);
        if (Math.abs(LH - RH) > 1) {
            return false;
        } else {
            return isBalanced(root.left) && isBalanced(root.right);
        }
    }


    /**
     * 层次遍历获取树的高度
     */
    private int getHigh(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int layer = 1;
        int nlayer = 0;
        int h = 0;
        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            layer--;
            if (tmp.left != null) {
                queue.offer(tmp.left);
                nlayer++;
            }
            if (tmp.right != null) {
                queue.offer(tmp.right);
                nlayer++;
            }
            if (layer == 0) {
                h++;
                layer = nlayer;
                nlayer = 0;
            }
        }
        return h;
    }

}
